package com.dounine.clouddisk360.parser.deserializer.diffpre;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.protocol.HttpClientContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

public class DifferPressResponseHandle implements ResponseHandler<DifferPress> {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(DifferPressResponseHandle.class);
	
	private HttpClientContext httpClientContext;
	public DifferPressResponseHandle(HttpClientContext httpClientContext) {
		this.httpClientContext = httpClientContext;
	}

	@Override
	public DifferPress handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
		Header[] headers = this.httpClientContext.getResponse().getAllHeaders();
		String localtion = null;
		for (Header header : headers) {
			if (header.getName().equals("Location")) {
				localtion = header.getValue();
				break;
			}
		}
		return desializer(localtion);
	}
	
	public String disassemblyResult(String result) {
		return String.format("{'redirectUrl':'%s'}", result);
	}
	
	public DifferPress desializer(String result) {
		if (StringUtils.isNotBlank(result)) {
			String differPressString = disassemblyResult(result);
			return JSON.parseObject(differPressString, DifferPress.class);
		}
		LOGGER.warn("分压主机地址解析请求为空");
		return new DifferPress();
	}

}
